package cn.cdu.medical.repository;

import cn.cdu.medical.entity.MedicalRecord;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 病历记录数据访问层
 */
@Mapper
public interface MedicalRecordMapper extends BaseMapper<MedicalRecord> {
    
    /**
     * 获取用户的病历列表
     * @param userId 用户ID
     * @return 病历列表
     */
    @Select("SELECT * FROM medical_record WHERE user_id = #{userId} ORDER BY visit_time DESC")
    List<MedicalRecord> findByUserId(String userId);
    
    /**
     * 获取医生的病历列表
     * @param doctorId 医生ID
     * @return 病历列表
     */
    @Select("SELECT * FROM medical_record WHERE doctor_id = #{doctorId} ORDER BY visit_time DESC")
    List<MedicalRecord> findByDoctorId(String doctorId);
    
    /**
     * 根据问诊ID获取病历
     * @param consultationId 问诊ID
     * @return 病历
     */
    @Select("SELECT * FROM medical_record WHERE consultation_id = #{consultationId} LIMIT 1")
    MedicalRecord findByConsultationId(String consultationId);

    /**
     * 获取患者的历史病历列表
     * @param patientId 患者ID
     * @param doctorId 医生ID（可选）
     * @param deptName 科室名称（可选）
     * @return 病历列表
     */
    @Select({
        "<script>",
        "SELECT m.* FROM medical_record m",
        "WHERE m.user_id = #{patientId}",
        "<if test='doctorId != null'>",
        "  AND (m.doctor_id = #{doctorId} OR m.dept_name = #{deptName})",
        "</if>",
        "ORDER BY m.visit_time DESC",
        "</script>"
    })
    List<MedicalRecord> findPatientHistoryRecords(String patientId, String doctorId, String deptName);
    
    /**
     * 获取患者最新的病历记录
     * @param patientId 患者ID
     * @return 最新的病历记录
     */
    @Select("SELECT * FROM medical_record WHERE user_id = #{patientId} ORDER BY visit_time DESC LIMIT 1")
    MedicalRecord findLatestByPatientId(String patientId);

    /**
     * 获取医生科室的患者病历列表
     * @param doctorId 医生ID
     * @param deptName 科室名称
     * @return 病历列表
     */
    @Select({
        "<script>",
        "SELECT * FROM medical_record m",
        "WHERE 1=1",
        "<if test='deptName != null and deptName != \"\"'>",
        "  AND (m.dept_name = #{deptName} OR m.dept_name IS NULL)",
        "</if>",
        "<if test='doctorId != null and doctorId != \"\"'>",
        "  AND (m.doctor_id = #{doctorId} OR m.doctor_id IS NULL)",
        "</if>",
        "ORDER BY m.visit_time DESC",
        "</script>"
    })
    List<MedicalRecord> findByDoctorDepartment(String doctorId, String deptName);
    
    /**
     * 获取有效的病历记录（数据较完整的记录）
     * @param userId 用户ID
     * @return 病历列表
     */
    @Select("SELECT * FROM medical_record WHERE user_id = #{userId} AND (patient_name IS NOT NULL OR diagnosis_name IS NOT NULL) ORDER BY visit_time DESC")
    List<MedicalRecord> findValidRecordsByUserId(String userId);
} 